﻿using AutoMapper.Internal.Mappers;
using DocumentFormat.OpenXml.Math;
using DocumentFormat.OpenXml.Wordprocessing;
using ERP.Common.Results;
using ERP.ERPSystem.HumanResources;
using ERP.ERPSystem.HumanResources.Dto;
using ERP.ERPSystem.ProductionSystem;
using ERP.Team.ProductionSystem;
using Grpc.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 生产系统-主数据-物料产品管理
    /// </summary>
    public class MaterialproductmanagementController : Controller
    {
        //物料产品管理接口
        IMaterialproductmanagementServices _materialproductmanagementServices;
        public MaterialproductmanagementController(IMaterialproductmanagementServices materialproductmanagementServices)
        {
            _materialproductmanagementServices = materialproductmanagementServices;
        }

        public IActionResult MaterialproductQuery()
        {
            return View();
        }
        /// <summary>
        /// 添加物料产品管理    
        /// </summary>
        /// <param name="materialproductDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddMaterialproductmanagement([FromBody] MaterialproductDTO materialproductDTO)
        {
            try
            {
                if (materialproductDTO == null)
                {
                    return Json(new { code = 1, msg = "无效的请求数据" });
                }

                var result = await _materialproductmanagementServices.AddMaterialproductmanagement(materialproductDTO);
                return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "添加成功" : "添加失败" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "服务器错误：" + ex.Message });
            }
        }
        /// <summary>
        /// 物料产品管理列表
        /// </summary>
        /// <param name="code">物料编码</param>
        /// <param name="name">物料名称</param>
        /// <param name="page">当前页</param>
        /// <param name="limit">页容量</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIPaging<MaterialproductModel>> GetMaterialproductModel(string? code, string? name, int page = 1, int limit = 10)
        {
            var result = await _materialproductmanagementServices.GetMaterialproductModel(code, name, page, limit);
            if (result == null)
            {
                result = new APIPaging<MaterialproductModel>
                {
                    PageCount = 0,
                    ListDate = new List<MaterialproductModel>(),
                    PageIndex = 0
                };
            }
            return result;

        }
        /// <summary>
        /// 自动生成物料编码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<string> GenerateMaterialCode()
        {
            Random rom = new Random();
            var code = rom.Next(10000000, 99999999);
            return code.ToString();
        }
        /// <summary>
        /// 根据ID获取物料产品详情
        /// </summary>
        /// <param name="id">物料产品ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMaterialproductById(int id)
        {
            try
            {
                var result = await _materialproductmanagementServices.GetMaterialproductById(id);
                if (result != null)
                {
                    return Json(new { code = 0, msg = "获取成功", data = result });
                }
                else
                {
                    return Json(new { code = 1, msg = "未找到指定的物料产品" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 更新物料产品管理
        /// </summary>
        /// <param name="materialproductDTO">物料产品DTO</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateMaterialproductmanagement([FromBody] MaterialproductDTO materialproductDTO)
        {
            try
            {
                if (materialproductDTO == null)
                {
                    return Json(new { code = 1, msg = "无效的请求数据" });
                }

                if (materialproductDTO.Id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的物料产品ID" });
                }

                if (string.IsNullOrEmpty(materialproductDTO.MaterielCode))
                {
                    return Json(new { code = 1, msg = "物料编码不能为空" });
                }

                if (string.IsNullOrEmpty(materialproductDTO.MaterielName))
                {
                    return Json(new { code = 1, msg = "物料名称不能为空" });
                }

                if (materialproductDTO.MaterielTypeId <= 0)
                {
                    return Json(new { code = 1, msg = "请选择物料分类" });
                }

                var result = await _materialproductmanagementServices.UpdateMaterialproductmanagement(materialproductDTO);
                return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "修改成功" : "修改失败" });
            }
            catch (Exception ex)
            {
                // 记录详细错误信息
                var errorMsg = $"更新物料产品失败: {ex.Message}";
                if (ex.InnerException != null)
                {
                    errorMsg += $" 内部异常: {ex.InnerException.Message}";
                }
                
                return Json(new { code = 1, msg = errorMsg });
            }
        }

        /// <summary>
        /// 删除物料产品
        /// </summary>
        /// <param name="id">物料产品ID</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DeleteMaterial(int id)
        {
            try
            {
                if (id <= 0)
                {
                    return Json(new { code = 1, msg = "无效的物料产品ID" });
                }

                var result = await _materialproductmanagementServices.DeleteMaterialproductmanagement(id);
                return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? "删除成功" : "删除失败" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除物料产品
        /// </summary>
        /// <param name="ids">物料产品ID列表</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> BatchDeleteMaterial([FromBody] List<int> ids)
        {
            try
            {
                if (ids == null || !ids.Any())
                {
                    return Json(new { code = 1, msg = "请选择要删除的记录" });
                }

                var result = await _materialproductmanagementServices.BatchDeleteMaterialproductmanagement(ids);
                return Json(new { code = result > 0 ? 0 : 1, msg = result > 0 ? $"成功删除{result}条记录" : "删除失败" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "批量删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        public IActionResult loadUrl([FromForm] IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return Json(new { code = 1, msg = "请选择要上传的文件" });
                }

                // 检查文件类型
                var allowedTypes = new[] { ".jpg", ".jpeg", ".png" };
                var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
                if (!allowedTypes.Contains(extension))
                {
                    return Json(new { code = 1, msg = "只允许上传jpg、jpeg、png格式的图片" });
                }

                // 检查文件大小（5MB）
                if (file.Length > 5 * 1024 * 1024)
                {
                    return Json(new { code = 1, msg = "文件大小不能超过5MB" });
                }

                // 确保目录存在
                var uploadPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "Materialproduct");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 生成新的文件名
                var fileName = $"{Guid.NewGuid()}{extension}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }

                // 返回文件的相对路径
                var relativePath = $"/images/Materialproduct/{fileName}";
                return Json(new { code = 0, msg = "上传成功", data = new { src = relativePath } });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "文件上传失败: " + ex.Message });
            }
        }
    }
}
